/**
 * Created by gongxun on 17/1/13.
 */

var PszTableLayer = GameCCSBase.extend({
    mPszCardLayer : null,
    mPszTableUILayer : null,
    mKwxApplyTableLayer : null,
    mPszTableRoomEndLayer : null,
    mPszTableReplayLayer : null,
    //timer
    Panel_timer : null,
    mProgressTimer : null,
    Image_timerBg : null,
    mTimeLeft : null,
    mCurrentSeat : null,
    //chipAll
    Image_chipAll : null,
    Text_chipAll : null,

    //牌桌状态 0录像 1正常打牌
    mPlayerType : null,

    //统计打了多少局
    mPlayGameCount : null,

    //游戏规则
    mGameConfig : null,

    //房间号
    mGroupId : null,

    //群号
    mGroupName : null,

    //录像号
    mReplayId : null,

    //密码
    mTableEnterPwd : null,

    //是否是创建者
    mIsRoomCreator : null,

    //结算消息（特殊处理）
    mPszRoundEndedEventzjh : null,

    ctor : function(){
        this._super();
        this.loadCocostudio("res/ccs/PszTable.json");
        mo.pszTable = this;
        this.mIsRoomCreator = false;
        mo.pszCardHelper.init();

        this.loadUI();
    },

    onEnter : function(){
        this._super();
        this.runAction(cc.sequence(cc.delayTime(1), cc.callFunc(function(){
            mo.soundHelper.playMusicGamePsz();
        })));

        mo.eventHelper.add("PszForceExitTableResponsepszOK", this, function () {
            if (mo.pszTable.mGameConfig.maxpan == mo.pszTableStatus.mTableStatus.LeftPlayTimes){
                mo.showMsgDialogOk("退出牌局成功", function(){
                    this.quitPszGame();
                }, this);
            }
        });

        mo.eventHelper.add("CancleJuRequestpsz", this, function(cancleJu){
            this.mKwxApplyTableLayer.updateCancelJuInfo(cancleJu);
        });
    },

    onExit : function(){
        mo.eventHelper.remove(this);
        this._super();
    },

    //正常打牌
    loadPlayCard : function(){
        this.mPlayGameCount = 0;
        this.mPlayerType = 1;
        this.mPszTableUILayer.intoShowIndex(10);

        //隐藏录像界面
        this.mPszTableReplayLayer.setVisible(false);

        //隐藏录像时候的ui
        this.mPszTableUILayer.setIsReplay(false);
    },

    //播放录像
    loadReplay : function(rePlaypsz, replayId){
        this.mPlayGameCount = 0;
        this.mPlayerType = 0;
        this.mPszTableUILayer.intoShowIndex(10);

        //录像规则
        mo.pszTable.setPszConfig(rePlaypsz.Result.CfgJson, "", "");

        //打开录像界面 并且播放
        this.mPszTableReplayLayer.setVisible(true);
        this.mPszTableReplayLayer.setReplayId(replayId);
        this.mPszTableReplayLayer.onStart();

        //隐藏录像时候的ui
        this.mPszTableUILayer.setIsReplay(true);

        this.mReplayId = replayId;
        mo.pszTableStatus.setReplayMsg(rePlaypsz);
        mo.pszTableStatus.playReplay();
    },

    //显示代开房人
    setShowRoomCreate : function(user){
        if (user != null){
            var kwxDaikaifangWidget = new KwxDaikaifangWidget();
            kwxDaikaifangWidget.setUserInfo(user);
            this.addChild(kwxDaikaifangWidget);
            kwxDaikaifangWidget.setPosition(cc.p(105, mo.gameSize.y - 10));
        }
    },

    loadUI : function(){
        //sprite
        cc.spriteFrameCache.addSpriteFrames("res/pszCards.plist", "res/pszCards.png");
        cc.spriteFrameCache.addSpriteFrames("res/pszChips.plist", "res/pszChips.png");
        cc.spriteFrameCache.addSpriteFrames("res/emojis.plist", "res/emojis.png");
        cc.spriteFrameCache.addSpriteFrames("res/emojis_index.plist", "res/emojis_index.png");

        //游戏牌层
        this.mPszCardLayer = new PszCardLayer();
        this.addChild(this.mPszCardLayer);

        //ui层
        this.mPszTableUILayer = new PszTableUILayer(mo.seekWidgetByName(this.ccsNode, "Panel_player"));
        this.addChild(this.mPszTableUILayer);

        //取消
        this.mKwxApplyTableLayer = new KwxApplyTableLayer("psz");
        this.addChild(this.mKwxApplyTableLayer);

        //录像层
        this.mPszTableReplayLayer = new PszTableReplayLayer();
        this.addChild(this.mPszTableReplayLayer);

        //倒计时背景
        this.Image_timerBg = mo.seekWidgetByName(this.ccsNode, "Image_timerBg");
        this.Image_timerBg.setVisible(false);
        this.Image_timerBg.runAction(cc.repeatForever(
            cc.sequence(
                cc.fadeIn(0.3),
                cc.fadeOut(1)
            )
        ));

        //倒计时
        this.Panel_timer = mo.seekWidgetByName(this.ccsNode, "Panel_timer");
        this.mProgressTimer = new cc.ProgressTimer(new cc.Sprite("res/ccs/psz/player_timer.png"));
        this.mProgressTimer.type = cc.ProgressTimer.TYPE_RADIAL;
        this.mProgressTimer.setReverseDirection(true);
        this.mProgressTimer.setVisible(false);
        this.mProgressTimer.setScale(0.88);
        this.Panel_timer.addChild(this.mProgressTimer);
        //开始倒计时
        this.schedule(this.updateCurrentSeat);

        //chipall
        this.Image_chipAll = mo.seekWidgetByName(this.ccsNode, "Image_chipAll");
        this.Image_chipAll.setVisible(false);
        this.Text_chipAll = mo.seekWidgetByName(this.ccsNode, "Text_chipAll");
    },

    setPszConfig : function(Cfgjson, tablePassWord, GroupName){
        this.mGroupName = GroupName;
        this.mTableEnterPwd = tablePassWord;
        this.mGameConfig = JSON.parse(Cfgjson);
        //密码
        if (mo.gameHelper.developerVersion == "3.0"){

            mo.gameHelper.setTextString(mo.seekWidgetByName(this.ccsNode, "Text_textRoomId"), "密码：");
            mo.gameHelper.setTextString(mo.seekWidgetByName(this.ccsNode, "Text_roomId"), "" + tablePassWord);
        }

        //生死局
        var Text_lod = mo.seekWidgetByName(this.ccsNode, "Text_lod");
        if (this.mGameConfig.lod != 0){
            mo.gameHelper.setTextString(Text_lod, "生死战:" + this.mGameConfig.lod);
            Text_lod.setVisible(true);
        }else{
            Text_lod.setVisible(false);
        }
    },

    quitPszGame : function(){
        if (mo.gameHelper.developerVersion == "2.0"){
            mo.sceneHelper.runSceneHall();
        }else if (mo.gameHelper.developerVersion == "3.0"){
            mo.sceneHelper.exitGameLayer();
            if (this.mGroupId != null){
                mo.hallLayer.intoGroup(this.mGroupId);
            }
        }
    },

    //大结算
    onShowJuEndedLayer : function(juEndedEventpsz){
        //判断是否需要直接退出 如果剩余局数和设置里面的局数一致 就直接退出
        var ruleJson = JSON.parse(juEndedEventpsz.CfgJson);

        if (mo.pszTableStatus.mTableStatus.LeftPlayTimes == ruleJson.maxpan){
            mo.showMsgDialogOk("牌局已经解散", function(){
                this.quitPszGame();
            }, this);
        }else{


            this.mPszTableRoomEndLayer = new PszTableRoomEndLayer();
            mo.sceneHelper.showEndInfoLayer(this.mPszTableRoomEndLayer);
            // this.addChild(this.mPszTableRoomEndLayer);
            this.mPszTableRoomEndLayer.setRoomEndInfo(juEndedEventpsz);

            if (juEndedEventpsz.EndFlag != 1){
                //自然结束 通过当局结算打开
                this.mPszTableRoomEndLayer.setVisible(false);
            }else{
                this.mPszTableRoomEndLayer.setVisible(true);
            }
        }
    },

    //更新剩余牌局 和规则
    updateLastPlayTimes : function(){
        //更新规则
        var time = mo.pszTableStatus.mTableStatus.LeftPlayTimes;
        if (time != null){
            time = this.mGameConfig.maxpan - time + 1;
            if (mo.pszTableStatus.mTableStatus.Step == 0){
                time -= 1;
            }

            mo.gameHelper.setTextString(mo.seekWidgetByName(this.ccsNode, "Text_leftJu"), "局数:" + time + "/" + this.mGameConfig.maxpan);
            mo.gameHelper.setTextString(mo.seekWidgetByName(this.ccsNode, "Text_roomId"), "房号:" + mo.pszTableStatus.mTableStatus.TableID);

            //men
            mo.gameHelper.setTextString(mo.seekWidgetByName(this.ccsNode, "Text_men"), "闷" + this.mGameConfig.men + "轮");

            //bipai
            mo.gameHelper.setTextString(mo.seekWidgetByName(this.ccsNode, "Text_bipai"), "比牌轮数:" + this.mGameConfig.bi);

            //fending
            var round = mo.pszTableStatus.mTableStatus.Round;
            if (mo.pszTableStatus.Step == 0){
                round = 0;
            }else{
                if (round > this.mGameConfig.open){
                    round = this.mGameConfig.open;
                }
            }
            mo.gameHelper.setTextString(mo.seekWidgetByName(this.ccsNode, "Text_fending"), "封顶轮数:" + round + "/" + this.mGameConfig.open);
        }
    },

    //邀请玩家
    onInvite : function(){
        var gameName = "psz";
        var configSummary = mo.gameHelper.getRuleConfigSummary(this.mGameConfig, gameName);
        configSummary += "，就等你来了(点击加入)";
        var tableId = mo.pszTableStatus.mTableStatus.TableID;

        var title = "桌号:[" + tableId + "]" + "-" + mo.gameHelper.projectName + "-拼三张";
        var description = configSummary;
        mo.gameHelper.onWxShareWeb(title, description, mo.gameUserInfo.getExternalUrl(1, tableId));
    },

    //分享录像
    onShareReplay : function(){
        var gameName = "psz";
        var configSummary = mo.gameHelper.getRuleConfigSummary(this.mGameConfig, gameName);
        configSummary += "，在游戏中输入录像id就能看到我的精彩回放了";

        var title = "录像id:" + this.mReplayId.substr(7) + "-" + mo.gameHelper.projectName + "-拼三张";
        var description = configSummary;

        mo.gameHelper.onWxShareWeb(title, description, mo.gameUserInfo.getExternalUrl(2, this.mReplayId.substr(7)));
    },

    //牌桌闪动
    onPlayTableOpAnim : function(){
        this.runAction(cc.sequence(
            cc.delayTime(0.50),
            cc.moveTo(0.05, cc.p(0, -15)),
            cc.moveTo(0.05, cc.p(0, 0)),
            cc.moveTo(0.03, cc.p(0, -10)),
            cc.moveTo(0.03, cc.p(0, 0))
        ));
    },

    //当前操作的玩家
    setCurrentSeat : function(seat){
        this.mPszTableUILayer.setCurrentSeat(seat);

        this.startTimeLeft(seat);
    },

    //开始倒计时
    startTimeLeft : function(seat){
        this.mTimeLeft = 15.0;
        this.mCurrentSeat = seat;

        this.mProgressTimer.setPosition(mo.pszCardHelper.seats[this.mCurrentSeat]);
        this.mProgressTimer.setPercentage(100);
        this.mProgressTimer.setVisible(true);

        this.Image_timerBg.setPosition(mo.pszCardHelper.seats[this.mCurrentSeat]);
        this.Image_timerBg.setVisible(false);
    },

    //停止倒计时
    stopTimeLeft : function(){
        this.mTimeLeft = null;
        this.mCurrentSeat = null;
        this.mProgressTimer.setVisible(false);
        this.Image_timerBg.setVisible(false);
    },

    //更新时间
    updateCurrentSeat : function(dt){
        if (this.mTimeLeft == null || this.mCurrentSeat == null){
            this.mProgressTimer.setVisible(false);
            return;
        }

        this.mTimeLeft -= dt;
        if(this.mTimeLeft < 0){
            this.mTimeLeft = 0;
            this.Image_timerBg.setVisible(true);
        }

        var percent = this.mTimeLeft / 15.0;
        this.mProgressTimer.setPercentage(percent * 100);
        this.mProgressTimer.setColor(cc.color(230 - 200 * percent, 253, 48));
    },

    //牌桌印象变化
    setTableStatusChange : function(){
        //停止显示比牌
        this.mPszCardLayer.setEndBipai();
    },

    //发牌
    fapai : function(seats, coins, cardNums){
        //重置
        this.mPszCardLayer.reset();
        this.mPszTableUILayer.reset();

        //发牌
        this.mPszCardLayer.fapai(seats, cardNums);

        //飞初始筹码
        for (var i = 0; i < 5; i++){
            if (coins[i] != null){
                this.xiazhu(i, coins[i], 1.5);
            }
        }

        //显示用户筹码控件
        this.mPszTableUILayer.fapai(seats);

        //显示闷牌控件
        if (mo.pszTableStatus.getFristRoundSee()){
            this.mPszCardLayer.mPszTableCardTControl.showSee(1.5);
        }else{
            this.mPszCardLayer.mPszTableCardTControl.showMen(1.5);
        }

        //当前操作的玩家
        this.mPszTableUILayer.setCurrentSeat(mo.pszTableStatus.getCurrentPlayer(), 1.5);
    },

    //下注动画
    xiazhu : function(seat, chipNum, delayTime){
        this.mPszCardLayer.xiazhu(seat, chipNum, delayTime);
    },

    //自己看牌
    kanpai : function(cardNums){
        this.mPszCardLayer.kanpai(cardNums);
    },

    //比牌
    bipai : function(seat0, seat1, winSeat, cardNumss0, cardNumss1){
        this.mPszCardLayer.bipai(seat0, seat1, winSeat, cardNumss0, cardNumss1);

        //隐藏操作按钮3.5秒
        this.mPszTableUILayer.bipai();
    },

    //显示其他玩家的手牌状态
    setPlayerInhandStatus : function(statuss){
        for (var i = 1; i < 5; i++){
            this.setPlayerSeatInhandStatus(i, statuss[i]);
        }
    },

    //显示玩家的手牌状态
    setPlayerSeatInhandStatus : function(seat, status, delayTime) {
        this.mPszTableUILayer.setPlayerSeatInhandStatus(seat, status, delayTime);
    },

    //结算
    jiesuan : function(winSeat, scores, cardTypes, cardNumss){
        //结算ui处理
        this.mPszCardLayer.mPszTableCardTControl.reset();
        this.mPszTableUILayer.reset();
        this.mPszCardLayer.setJiesuanGray();

        //牌型
        for (var i = 0; i < 5; i++){
            if (cardTypes[i] != null){
                this.mPszTableUILayer.setCardType(i, cardTypes[i]);
            }
        }

        //翻牌动画
        for (var i = 0; i < 5; i++){
            if (cardNumss[i] != null && this.mPszCardLayer.mCardss[i][0].mCardNum == 0){
                this.mPszCardLayer.fanpai(i, cardNumss[i]);
            }
        }

        //飞筹码动画
        this.mPszCardLayer.setWinChips(winSeat);
    },

    //保存结算消息
    setJuesaunInfo : function(pszRoundEndedEventzjh){
        this.mPszRoundEndedEventzjh = pszRoundEndedEventzjh;
        this.handlerJuesaunInfo(mo.pszTableStatus.mTableStatus);
    },

    //触发结算消息
    handlerJuesaunInfo : function(tableStatus){
        if (this.mPszRoundEndedEventzjh != null){
            var endInfo = this.mPszRoundEndedEventzjh;
            this.mPszRoundEndedEventzjh = null;

            //开始处理
            var isTeshu = false;

            //计算时间
            var delayTime = 0;

            var LastAction = tableStatus.LastAction;
            if (LastAction.code == 1 || LastAction.code == 2 || LastAction.code == 3){
                delayTime = 1;
            }else if (LastAction.code == 4){
                delayTime = 4;
                isTeshu = true;
            }else if (LastAction.code == 5){
                delayTime = 1;
                isTeshu = true;
            }

            //结算动画
            this.scheduleOnce(function(dt){
                var winseat = mo.pszTableStatus.getViewForLogic(endInfo.WinSeat - 1, endInfo.MySeat - 1);
                var scores = [null, null, null, null, null];
                var cardTypes = [null, null, null, null, null];
                var cardNumss = [null, null, null, null, null];
                for (var i = 0; i < 5; i++){
                    var logicSeat = mo.pszTableStatus.getLogicForView(i, endInfo.MySeat - 1);
                    var seatUser = endInfo["SeatUser" + (logicSeat + 1)];
                    if (seatUser != null){
                        //score
                        var allfen = 0;
                        var ids = seatUser.LostWin.ItemTypes;
                        var nums = seatUser.LostWin.ItemNums;
                        allfen = mo.gameUserInfo.getItemNum(ids, nums, 0);
                        scores[i] = allfen;

                        var type = mo.pszTableStatus.getCardType(seatUser.Cardtype);
                        var cardNums = seatUser.HandCards;
                        if (type != null && cardNums.length != 0){
                            //type
                            cardTypes[i] = type;

                            //cardNums
                            cardNumss[i] = cardNums;
                        }
                    }
                }

                mo.pszTable.jiesuan(winseat, scores, cardTypes, cardNumss);
            }, delayTime);

            //结算界面
            mo.pszTable.mPszTableUILayer.mPszTableEndLayer.setEndInfo(endInfo, delayTime + 2);
        }
    }
});